﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Newtonsoft.Json.Linq;
using System.Text.Json;

namespace Tools.ViewModels;

public partial class JsonViewModel : ViewModelBase
{
    [ObservableProperty]
    private string? inputJson;

    [ObservableProperty]
    private string? formattedJson;

    [RelayCommand]
    private void Format()  
    {
        FormattedJson =NewtonsoftFormatJson(InputJson);
    }

    /// <summary>
    /// 使用 System.Text.Json 格式化 JSON 字符串
    /// </summary>
    /// <param name="raw"></param>
    /// <returns></returns>
    private static string FormatJson(string raw)
    {
        if (string.IsNullOrWhiteSpace(raw)) return raw;
        try
        {
            using var doc = JsonDocument.Parse(raw);
            return JsonSerializer.Serialize(doc.RootElement,new JsonSerializerOptions { WriteIndented = true });
        }
        catch
        {
            return raw; 
        }
    }

    /// <summary>
    /// 使用 Newtonsoft.Json 格式化 JSON 字符串
    /// </summary>
    /// <param name="raw"></param>
    /// <returns></returns>
    private string NewtonsoftFormatJson(string raw)
    {
        if (string.IsNullOrWhiteSpace(raw)) return raw;
        try
        {
            var token = Newtonsoft.Json.Linq.JToken.Parse(raw);
            return token.ToString(Newtonsoft.Json.Formatting.Indented);
        }
        catch
        {
            return raw;
        }
    }
}
